1948G - MST with Matching - CodeForces Solution


bitmasks brute force dsu trees

Please click on ads to support us..

Python Code:

def get_root(v, fa):
    if fa[v] == v: return v
    fa[v] = get_root(fa[v], fa)
    return fa[v]
n, c = map(int, input().split())
e = [list(map(int, input().split())) for _ in range(n)]
edge = [(e[i][j], i, j) for i in range(n) for j in range(i + 1, n) if e[i][j] > 0]
edge.sort()
inf = float('inf'); ans = inf
for i in range(1, 1 << n):
    now = bin(i).count('1') * c; fa = list(range(n)); tot = n
    for w, u, v in edge:
        if now > ans: break
        if ((i >> u) & 1) or ((i >> v) & 1):
            u = get_root(u, fa); v = get_root(v, fa)
            if u == v: pass
            else: fa[u] = v; now += w; tot -= 1
    if tot == 1: ans = min(ans, now)
print(ans)


Comments

Submit
0 Comments
More Questions

1326B - Maximums
1635C - Differential Sorting
961A - Tetris
1635B - Avoid Local Maximums
20A - BerOS file system
1637A - Sorting Parts
509A - Maximum in Table
1647C - Madoka and Childish Pranks
689B - Mike and Shortcuts
379B - New Year Present
1498A - GCD Sum
1277C - As Simple as One and Two
1301A - Three Strings
460A - Vasya and Socks
1624C - Division by Two and Permutation
1288A - Deadline
1617A - Forbidden Subsequence
914A - Perfect Squares
873D - Merge Sort
1251A - Broken Keyboard
463B - Caisa and Pylons
584A - Olesya and Rodion
799A - Carrot Cakes
1569B - Chess Tournament
1047B - Cover Points
1381B - Unmerge
1256A - Payment Without Change
908B - New Year and Buggy Bot
979A - Pizza Pizza Pizza
731A - Night at the Museum